package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.util.DateUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.mapper.OmsPlatformOrderMapper;
import com.settlement.system.model.entity.OmsPlatformOrder;
import com.settlement.system.model.entity.SysOmsOrderLink;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.form.OmsPlatformOrderForm;
import com.settlement.system.model.query.OmsPlatformOrderQuery;
import com.settlement.system.model.vo.OmsPlatformOrderImportVo;
import com.settlement.system.service.OmsPlatformOrderService;
import com.settlement.system.service.SnowflakeIdWorker;
import com.settlement.system.service.SysOmsOrderLinkService;
import com.settlement.system.service.SysStoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * OMS平台订单 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2024-05-06
 */
@Service
@RequiredArgsConstructor
public class OmsPlatformOrderServiceImpl extends ServiceImpl<OmsPlatformOrderMapper, OmsPlatformOrder> implements OmsPlatformOrderService {

    private final SysOmsOrderLinkService sysOmsOrderLinkService;

    private final SysStoreService storeService;

    private final RedisTemplate redisTemplate;

    private final SnowflakeIdWorker snowflakeIdWorker = SnowflakeIdWorker.getInstance();

    @Override
    public Page<OmsPlatformOrder> getPage(OmsPlatformOrderQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 拼接月份列表
        List<String> monthList = new ArrayList<>();
        String endMonthStr = queryParams.getEndMonth().replaceAll("-", "");
        LocalDate endMonth = LocalDate.parse(endMonthStr + "01", DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate startTime = LocalDate.parse(queryParams.getStartMonth().replaceAll("-", "") + "01", DateTimeFormatter.ofPattern(
                "yyyyMMdd"));
        // 获取已经生成的表名
        Object object = redisTemplate.opsForValue().get(SystemConstants.OMS_PLATFORM_ORDER);
        List<String> tableNameList;
        if(object != null){
            tableNameList = (List<String>) object;
        }else{
            tableNameList = this.baseMapper.getAllTable();
            // 添加缓存
            redisTemplate.opsForValue().set(SystemConstants.OMS_PLATFORM_ORDER, tableNameList, 1, TimeUnit.HOURS);
        }
        // 循环追加月份
        while (!startTime.isAfter(endMonth)) {
            monthList.add(startTime.format(DateTimeFormatter.ofPattern("yyyyMM")));
            startTime = startTime.plusMonths(1);
        }
        // 根据月份判断数据库表是否存在
        List<String> existTableList = new ArrayList<>();
        String tableName;
        for (String month : monthList) {
            tableName = "oms_platform_order_%s".formatted(month);
            if (tableNameList.contains(tableName)) {
                existTableList.add(tableName);
            }
        }

        Page<OmsPlatformOrder> page = new Page<>(pageNum, pageSize);
        queryParams.setTableNameList(existTableList);
        // 查询数据
        if(existTableList.size() == 0){
            return page;
        }
        return this.baseMapper.getPage(page, queryParams);
    }

     @Override
     public boolean saveOmsPlatformOrder(OmsPlatformOrderForm omsPlatformOrderForm) {
         OmsPlatformOrder omsPlatformOrder = new OmsPlatformOrder();
         BeanUtil.copyProperties(omsPlatformOrderForm, omsPlatformOrder);
         omsPlatformOrder.setCreateTime(null);
         return this.saveOrUpdate(omsPlatformOrder);
     }

     @Override
     public OmsPlatformOrderForm getOmsPlatformOrderFormData(Long id) {
         OmsPlatformOrder omsPlatformOrder = this.getById(id);
         OmsPlatformOrderForm omsPlatformOrderForm = new OmsPlatformOrderForm();
         BeanUtil.copyProperties(omsPlatformOrder, omsPlatformOrderForm);
         return omsPlatformOrderForm;
     }

     @Override
     public boolean deleteOmsPlatformOrder(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
     }

    @Override
    public void importData(List<OmsPlatformOrderImportVo> voList, String storeCode)  {
        SysStore sysStore = storeService.getByCode(storeCode);
        Assert.isTrue(Objects.nonNull(sysStore), "店铺不存在");
        List<String> billMonthList = new ArrayList<>();
        List<String> billNoList = voList.stream().map(OmsPlatformOrderImportVo::getSourcePreformSubNo).distinct().collect(Collectors.toList());
        String billMonth;
        for (OmsPlatformOrderImportVo sysTmOrderImportVo : voList) {
            billMonth = DateUtils.formatDate(DateUtils.convertStringToLocalDateTime(sysTmOrderImportVo.getOrderCreateTime()));
            sysTmOrderImportVo.setBillMonth(billMonth);
            if (!billMonthList.contains(billMonth)) {
                billMonthList.add(billMonth);
            }
        }
        List<OmsPlatformOrder> omsPlatformOrders = new ArrayList<>();
        // 查出历史记录
        OmsPlatformOrder omsPlatformOrder;
        List<OmsPlatformOrder> sysOmsOrders;
        for (String bMonth : billMonthList) {
            omsPlatformOrder = new OmsPlatformOrder();
            omsPlatformOrder.setTableName("oms_platform_order_%s".formatted(bMonth));
            // 检查是否存在表
            if (!StringUtils.hasText(this.baseMapper.existTable(omsPlatformOrder.getTableName()))) {
                this.baseMapper.createTable(omsPlatformOrder.getTableName());
                // 删除表缓存
                redisTemplate.delete(SystemConstants.OMS_PLATFORM_ORDER);
            }else{
                omsPlatformOrder.setSourcePreformSubNoList(billNoList);
                sysOmsOrders = this.baseMapper.getList(omsPlatformOrder);
                if (sysOmsOrders.size() > 0) {
                    for (OmsPlatformOrder omsOrder : sysOmsOrders) {
                        omsOrder.setTableName(omsPlatformOrder.getTableName());
                    }
                    omsPlatformOrders.addAll(sysOmsOrders);
                }
            }
        }
        List<SysOmsOrderLink> sysOmsOrderLinkList = new ArrayList<>();
        SysOmsOrderLink link;
        for (OmsPlatformOrderImportVo importVo : voList) {
            omsPlatformOrder = omsPlatformOrders.stream().filter(item -> item.getSourcePreformSubNo().equalsIgnoreCase(importVo.getSourcePreformSubNo())).findFirst().orElse(null);
            boolean hasRecord = true;
            if (omsPlatformOrder == null) {
                hasRecord = false;
                omsPlatformOrder = new OmsPlatformOrder();
                omsPlatformOrder.setId(snowflakeIdWorker.nextId(importVo.getBillMonth()));
            }
            BeanUtil.copyProperties(importVo, omsPlatformOrder, "id");
            link = new SysOmsOrderLink();
            link.setLinkNo(omsPlatformOrder.getSourcePreformSubNo());
            link.setTableId(omsPlatformOrder.getId());
            sysOmsOrderLinkList.add(link);
            // 如果主单号和子单号不一样，则需要保存两份数据
            if (!omsPlatformOrder.getSourcePreformSubNo().equalsIgnoreCase(omsPlatformOrder.getSourcePreformMainNo())) {
                link = new SysOmsOrderLink();
                link.setLinkNo(omsPlatformOrder.getSourcePreformMainNo());
                link.setTableId(omsPlatformOrder.getId());
                sysOmsOrderLinkList.add(link);
            }
            omsPlatformOrder.setTableName("oms_platform_order_%s".formatted(importVo.getBillMonth()));
            omsPlatformOrder.setStoreId(sysStore.getId());
            if(hasRecord){
                this.baseMapper.update(omsPlatformOrder);
            }else{
                this.baseMapper.insertData(omsPlatformOrder);
            }
        }
        for (SysOmsOrderLink sysOmsOrderLink : sysOmsOrderLinkList) {
            try{
                sysOmsOrderLinkService.saveOrUpdate(sysOmsOrderLink);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<OmsPlatformOrderImportVo> findByIds(String idsStr) {
        if (StrUtil.isBlank(idsStr)) {
            return new ArrayList<>();
        }
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<OmsPlatformOrder> omsPlatformOrderList = this.getBaseMapper().selectBatchIds(ids);
        List<OmsPlatformOrderImportVo> voList = new ArrayList<>();
        for (OmsPlatformOrder omsPlatformOrder : omsPlatformOrderList) {
            OmsPlatformOrderImportVo vo = new OmsPlatformOrderImportVo();
            BeanUtil.copyProperties(omsPlatformOrder, vo);
            voList.add(vo);
        }
        return voList;
    }
}
